package com.example.day05_uibestpractice;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private List<Msg> msgList = new ArrayList<>();
    private EditText inputText;
    private Button send;
    private RecyclerView msgRecyclerView;
    private MsgAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initMsgs();
        inputText = findViewById(R.id.input_text);
        send = findViewById(R.id.send);

        msgRecyclerView = findViewById(R.id.msg_recycler_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        msgRecyclerView.setLayoutManager(layoutManager);
        adapter = new MsgAdapter(msgList);
        msgRecyclerView.setAdapter(adapter);

        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = inputText.getText().toString();
                if(!"".equals(content)){
                    msgList.add(new Msg(content, Msg.TYPE_SENT));
                    adapter.notifyItemInserted(msgList.size()-1);  //当有新消息时，刷新RecyclerView中的显示
                    msgRecyclerView.scrollToPosition(msgList.size()-1);  //定位到最后一行
                    inputText.setText("");  //清空输入框
                }
            }
        });

    }

    private void initMsgs(){
        msgList.add(new Msg("Knock, knock !", Msg.TYPE_RECEIVED));
        msgList.add(new Msg("Who's there ?", Msg.TYPE_SENT));
        msgList.add(new Msg("Ice cream.", Msg.TYPE_RECEIVED));
        msgList.add(new Msg("Ice cream who ?", Msg.TYPE_SENT));
        msgList.add(new Msg("Ice cream (I scream) so loud,", Msg.TYPE_RECEIVED));
        msgList.add(new Msg(" windows will break !", Msg.TYPE_RECEIVED));
    }
}
